<template>
  <div class="department-container">
    <div class="app-container">
      <!-- pagetools 公共组件 -->
      <pageTools>>
        <template #title>
          <span>总记录条数:{{ total }}条</span>
        </template>
        <template #button>
          <el-button type="primary" size="small" @click="dialogFormVisible=true">新增员工</el-button>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/employees/upload')">导入excel</el-button>
          <el-button v-allow="'export'" type="danger" size="small" @click="hExport">导出excel</el-button>
        </template>
      </pageTools>
      <!-- 内容 -->
      <el-card style="margin-top:15px">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formOfEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${scope.row.id}`)">查看</el-button>
              <el-button v-allow="'allotUser'" type="text" size="small" @click="assign(scope.row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="block" style="text-align: center; margin-top: 15px;">
          <el-pagination
            background
            :current-page="pageParams.page"
            :page-sizes="[1, 3, 5, 10]"
            :page-size="pageParams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 新增员工弹出框 -->
    <el-dialog
      title="收货地址"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <diaLog v-if="dialogFormVisible" @close="dialogFormVisible=false" @success="isAdd" />
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="showRoleDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assign-role v-if="showRoleDialog" :id="userId" @close="showRoleDialog=false" />
    </el-dialog>
  </div>
</template>

<script>
// 分配角色表单子组件
import AssignRole from './assignRole.vue'
//  新增员工表单子组件
import diaLog from './dialog.vue'
import { getEmployee, delEmployee, addEmployee } from '@/api/employees'
// 导入枚举文件
import EmployeeEnum from '@/constant/employees'
const hireType = EmployeeEnum.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
export default {
  name: '',
  components: { diaLog, AssignRole },
  props: {},
  data() {
    return {
      userId: '', // 当前角色id
      showRoleDialog: false, // 分配角色 显示隐藏
      dialogFormVisible: false, // 新增角色显示隐藏
      list: [],
      total: 0,
      pageParams: {
        page: 1,
        size: 5
      }

    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
  },
  mounted() {},
  methods: {
    // 动态排序
    indexMethod(index) {
      return (this.pageParams.page - 1) * this.pageParams.size + index + 1
    },
    // 页码
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.getList()
    },
    // 每页数据条数
    handleSizeChange(val) {
      this.pageParams.size = val
      this.getList()
    },
    // 枚举形式
    formOfEmployment(num) {
      return hireType[num]
    },
    // 获取数据
    async getList() {
      try {
        const res = await getEmployee(this.pageParams)
        // console.log(res.data)
        this.total = res.data.total
        res.data.rows.forEach(item => {
          item.timeOfEntry = item.timeOfEntry.substr(0, 10)
        })
        this.list = res.data.rows
      } catch (err) {
        console.log(err)
        this.$message.error('获取数据失败')
      }
    },
    // 删除员工
    async isDel(id) {
      try {
        await delEmployee(id)
        this.$message({ type: 'success', message: '删除成功!' })
        // 更改分页数据
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 重新渲染
        this.getList()
      } catch (err) {
        console.log('删除失败', err)
        this.$message.error('删除失败')
      }
    },
    // 点击删除按钮
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.isDel(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加员工
    async isAdd(data) {
      try {
        await addEmployee(data)
        // console.log(res)
        this.$message.success('添加成功')
        // 关闭弹框
        this.dialogFormVisible = false
        // 更新页码
        this.pageParams.page = Math.ceil(++this.total / this.pageParams.size)
        // 重新渲染
        this.getList()
      } catch (err) {
        console.log('添加失败', err)
        this.message.error('添加失败')
      }
    },
    // 导出员工
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        // 发ajax请求，获取数据
        const res = await getEmployee(this.pageParams)
        const list = res.data.rows
        console.log('从后端获取的数据', list)

        const { header, data } = this.formatData(list)
        // excel表示导入的模块对象
        console.log(header, data)
        excel.export_json_to_excel({
          // header: ['姓名', '工资'], // 表头 必填
          header: header, // 表头 必填
          data: data,
          // data: [
          //   ['刘备11111111111111', 100],
          //   ['关羽', 500]
          // ], // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 转换后端数据的处理函数
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    // 分配角色
    assign(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }
}
</script>

<style scoped lang='less'>

</style>
